#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

static char usrdata[] = {"usr data!"};

void usage_info(void)
{
	printf("\n");
	printf("+++++++++++++++++++++++++++++++++++++++++\n");
	printf("+       help information  @sumu          +\n");
	printf("+++++++++++++++++++++++++++++++++++++++++\n");

	printf("help:\n");
	printf("use format: ./app_name /dev/device_name arg1 ... \n");
	printf("            ./chrdev_data_exchange_demo_app.out /dev/sdevice 1 # 读取 \n");
	printf("            ./chrdev_data_exchange_demo_app.out /dev/sdevice 2 # 写入 \n");
	printf("\n");

	printf("command info:\n");
	printf("  (1)load module  : insmod module_name.ko\n");
	printf("  (2)unload module: rmmod module_name.ko\n");
	printf("  (3)show module  : lsmod\n");
	printf("  (4)view device  : cat /proc/devices\n");
	printf("  (5)create device node: mknod /dev/device_name c major_num secondary_num \n");
	printf("  (6)show device node  : ls /dev/device_name \n");
	printf("  (7)show device vlass  : ls /sys/class \n");
	printf("+++++++++++++++++++++++++++++++++++++++++\n");
}

int main(int argc, char *argv[])
{
    int fd = -1;
    int ret = 0;
    char *filename = NULL;
    char readbuf[100] = {0};
    char writebuf[100] = {0};

    if (argc != 3)
    {
        usage_info();
        return -1;
    }

    filename = argv[1];

    /* 打开驱动文件 */
    fd = open(filename, O_RDWR);
    if (fd < 0)
    {
        printf("can't open file %s !\n", filename);
        return -1;
    }


    if (atoi(argv[2]) == 1)
    { 
        /* 从驱动文件读取数据 */
        ret = read(fd, readbuf, 32);
        if (ret < 0)
        {
            printf("read file %s failed!\n", filename);
        }

        /*  读取成功，打印出读取成功的数据 */
        printf("read data \"%s\" from %s !\n", readbuf, filename);

    }

    if (atoi(argv[2]) == 2)
    {
        /* 向设备驱动写数据 */
        memcpy(writebuf, usrdata, sizeof(usrdata));
        ret = write(fd, writebuf, 32);
        if (ret < 0)
        {
            printf("write file %s failed!\n", filename);
        }

        printf("write \"%s\" to %s success!\n", usrdata, filename);
    }

    /* 关闭设备 */
    ret = close(fd);
    if (ret < 0)
    {
        printf("can't close file %s !\n", filename);
        return -1;
    }

    return 0;
}
